package net.TCPMORE;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Receiver {
    public static final List<Socket> OnlineSocket =  new ArrayList<>();
    public static void main(String[] args) throws Exception {
        ServerSocket socket = new ServerSocket(6666);
        while (true) {
            Socket accept = socket.accept();
            OnlineSocket.add(accept);
            //把这个客户端对应的socket通信管道，交给一个独立的线程负责处理
            new Thread(() -> {
                try (InputStream inputStream = accept.getInputStream();
                     DataInputStream dis = new DataInputStream(inputStream);
                     ){
                    while (true) {
                        String s = dis.readUTF();
                        System.out.println(s);
                        for (Socket socket1 : OnlineSocket) {
                            try (OutputStream outputStream = socket1.getOutputStream();
                                 DataOutputStream dos = new DataOutputStream(outputStream);
                                 ){
                                dos.writeUTF(s);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                } catch (IOException e) {
                    System.out.println("有人下线了");
                    OnlineSocket.remove(accept);
                }
            }).start();
        }
    }
}
